<template>
  <div class="auth-container">
    <div class="auth-card">
      <h2><i class="fas fa-user-plus mr-2"></i>注册新账号</h2>
      
      <div v-if="errorMessage" class="alert alert-danger">
        {{ errorMessage }}
      </div>
      
      <div v-if="successMessage" class="alert alert-success">
        {{ successMessage }}
      </div>
      
      <form @submit.prevent="handleRegister">
        <div class="form-group">
          <label>用户名</label>
          <input 
            type="text" 
            class="form-control" 
            v-model="formData.username"
            placeholder="请输入用户名"
            required
          />
        </div>
        
        <div class="form-group">
          <label>邮箱（可选）</label>
          <input 
            type="text" 
            class="form-control" 
            v-model="formData.email"
            placeholder="可选，可以留空"
          />
        </div>
        
        <div class="form-group">
          <label>密码</label>
          <input 
            type="password" 
            class="form-control" 
            v-model="formData.password"
            placeholder="请输入密码"
            required
          />
        </div>
        
        <div class="form-group">
          <label>以太坊地址 (EOA)</label>
          <div class="input-group">
            <input 
              type="text" 
              class="form-control" 
              v-model="formData.eoaAddress"
              placeholder="0x..."
              required
              readonly
            />
            <div class="input-group-append">
              <button 
                type="button" 
                class="btn btn-warning"
                @click="connectWallet"
              >
                <i class="fas fa-wallet mr-1"></i>连接钱包
              </button>
            </div>
          </div>
          <small class="form-text text-muted">
            请先安装 MetaMask 插件并连接钱包
          </small>
        </div>
        
        <button type="submit" class="btn btn-primary" :disabled="loading || !formData.eoaAddress">
          <span v-if="loading">
            <i class="fas fa-spinner fa-spin mr-2"></i>注册中...
          </span>
          <span v-else>
            <i class="fas fa-user-plus mr-2"></i>注册
          </span>
        </button>
      </form>
      
      <div class="text-center mt-3">
        <p class="text-muted">已有账号？</p>
        <router-link to="/login" class="btn btn-outline-primary">
          <i class="fas fa-sign-in-alt mr-2"></i>立即登录
        </router-link>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref } from 'vue'
import { useRouter } from 'vue-router'
import { useAuthStore } from '@/stores/auth'

const router = useRouter()
const authStore = useAuthStore()

const formData = ref({
  username: '',
  email: '',
  password: '',
  eoaAddress: ''
})

const loading = ref(false)
const errorMessage = ref('')
const successMessage = ref('')

const connectWallet = async () => {
  if (typeof window.ethereum !== 'undefined') {
    try {
      // 使用 window.ethereum 直接请求账户（更简单可靠）
      const accounts = await window.ethereum.request({ method: 'eth_requestAccounts' })
      formData.value.eoaAddress = accounts[0]
      successMessage.value = '钱包连接成功！'
      setTimeout(() => successMessage.value = '', 3000)
    } catch (error) {
      errorMessage.value = '连接钱包失败：' + error.message
    }
  } else {
    errorMessage.value = '请先安装 MetaMask 插件！'
  }
}

const handleRegister = async () => {
  loading.value = true
  errorMessage.value = ''
  
  try {
    const response = await authStore.register(formData.value)
    
    if (response.success) {
      successMessage.value = '注册成功！正在跳转...'
      setTimeout(() => {
        router.push('/')
      }, 1500)
    } else {
      errorMessage.value = response.message
    }
  } catch (error) {
    errorMessage.value = '注册失败，请稍后重试'
  } finally {
    loading.value = false
  }
}
</script>

<style scoped>
.auth-card {
  animation: slideIn 0.5s ease-out;
}

@keyframes slideIn {
  from {
    opacity: 0;
    transform: translateY(-20px);
  }
  to {
    opacity: 1;
    transform: translateY(0);
  }
}

.input-group-append .btn {
  border-top-left-radius: 0;
  border-bottom-left-radius: 0;
}
</style>

